<script setup>
// PTV分析(产量差异)
import { ref, onMounted } from 'vue'

const fetchPtvData = async () => {
	try {
		const response = await fetch('http://localhost/api/ads-ptv')
		const data = await response.json()

		chartOption.value.xAxis[0].data = data.map(d => d.brand)
		chartOption.value.series[0].data = data.map(d => d.annualPlanned)
		chartOption.value.series[1].data = data.map(d => d.annualActual)
		chartOption.value.series[2].data = data.map(d => d.annualVarianceRate)
	} catch (error) {
		console.error('PTV数据获取失败:', error)
	}
}

onMounted(fetchPtvData)

const chartOption = ref({
	backgroundColor: 'transparent', // 透明背景以适配深色主题
	legend: {
		top: '10%',
	},
	tooltip: {
		trigger: 'axis',
		axisPointer: {
			type: 'cross',
			crossStyle: {
				color: '#999',
			},
		},
		valueFormatter: function (value) {
			return (value / 10000).toFixed(2) + '万'
		},
	},
	grid: {
		top: '25%',
		left: '5%',
		right: '5%',
		bottom: '10%',
		containLabel: true,
	},
	xAxis: [
		{
			type: 'category',
			data: [' '],
			axisLabel: { color: 'white' },
			axisPointer: { type: 'shadow' },
		},
	],
	yAxis: [
		{
			type: 'value',
			name: '目标值（万）',
			splitLine: { show: false },
			axisLabel: {
				color: 'white',
				formatter: function (value) {
					return (value / 10000).toFixed(0)
				},
			},
			splitNumber: 4,
		},
		{
			type: 'value',
			axisLabel: { color: 'white', formatter: '{value} %' },
			splitLine: { show: false },
			splitNumber: 2,
		},
	],
	series: [
		{
			name: '累计目标',
			type: 'bar',
			itemStyle: {
				normal: {
					barBorderRadius: [3, 3, 0, 0],
				},
				shadowColor: 'rgba(0, 0, 0, 0.1)',
			},
			data: Array.from({ length: 10 }, () => Math.random() * 100),
		},
		{
			name: '累计完成',
			type: 'bar',
			itemStyle: {
				normal: {
					barBorderRadius: [3, 3, 0, 0],
				},
				shadowColor: 'rgba(0, 0, 0, 0.1)',
			},
			data: Array.from({ length: 10 }, () => Math.random() * 100),
		},
		{
			name: '目标差异率',
			type: 'line',
			yAxisIndex: 1,
			tooltip: {
				valueFormatter: function (value) {
					return value + '%'
				},
			},
			data: Array.from({ length: 10 }, () => Math.random() * 0.2),
		},
	],
})
</script>

<template>
	<v-chart theme="chalk" :option="chartOption" />
</template>
